import { useState, useEffect } from 'react'
import Bottom from "../../components/bottom"
import formatNum from '../../utils/money'
import { Switch, Swiper, Popup, Button, Toast } from "antd-mobile"
import ToastBase from "../../components/toast"
import Home from "../../api/home"
import Wish from "../../api/wish"
import style from "./style.module.scss"
import { useNavigate } from 'react-router-dom'
const { header, search, btn, content, title, nav, navBox, main, totalPrice, goodsItem, proInfo, active, wishBox, wishItem } = style

const Explore = () => {
  const navigate = useNavigate()
  const [userid] = useState(sessionStorage.getItem("userid") || "")
  const [navData, setNavData] = useState([])
  const [obj, setObj] = useState<any>()
  const [toastShow, setToastShow] = useState(false)
  const [img, setImg] = useState("")
  const [wishName, setWishName] = useState<any>()
  const [goodsData, setGoodsData] = useState<any>([])
  const [userGoodsData, setUserGoodsData] = useState<any>([])
  const [wishData, setWishData] = useState<any>([])
  const [index, setIndex] = useState(0)
  const [visible, setVisible] = useState(false)
  const [visible2, setVisible2] = useState(false)
  const [categoryId, setCategoryId] = useState(1)
  const [height, setHeight] = useState(64)
  const [heartArr, setHeartArr] = useState<any>([])



  const getNavData = async () => {
    let res = await Home["getNav"]()
    if (res.status === 200) {
      setNavData(res.data)
    }
  }

  const getWishData = async () => {
    let res = await Wish["getwList"](userid)
    if (res.status === 200) {
      setWishData(res.data)
      let newArr: any = []
      res.data.forEach((item: any) => {
        item.children.forEach((itm: any) => {
          newArr = [...newArr, itm.id]
          setHeartArr(newArr)
        })
      })
    }
  }



  const addWish = async (row: any) => {
    if (sessionStorage.getItem("userid") === null) {
      Toast.show({
        content: "您还没有登录，不能收藏哦~",
        icon: "fail",
        afterClose: () => {
          navigate("/login")

        }
      })
      return
    }
    getWishData()
    setObj(row)
    setImg(row.banners[0])
    if (row.isHeart) {
      setUserGoodsData(userGoodsData.map((item: any) => {
        if (item.id === row.id) {
          item.isHeart = false
        }
        return item
      }))
      let res2 = await Wish["removewListChild"]({ userid, proid: row.id })
      
      if (res2?.code === 200) {
        setWishName({ name1: "删除自", name2: res2.data.data.title })
        setToastShow(true)
        setTimeout(() => {
          setToastShow(false)
        }, 3000)
      }
    } else {
      setVisible(true)
      setUserGoodsData(userGoodsData.map((item: any) => {
        if (item.id === row.id) {
          item.isHeart = true
        }
        return item
      }))
    }
  }

  const addWishListChildren = async (row: any) => {

    let res = await Wish["addwListChild"]({ id: row.id, data: [...row.children, obj] })
    if (res.code === 200) {
      setVisible(false)
      setWishName({ name1: "已保存自", name2: row.title })
      setToastShow(true)
      setTimeout(() => {
        setToastShow(false)
      }, 3000)
    }
  }

  const getGoodsData = async () => {
    let res = await Home["getGoods"]()
    if (res.status === 200) {
      setGoodsData(res.data)
    }
  }

  const addWishList = async () => {
    let res = await Wish["addwList"]({ id: userid, children: obj, title: wishName.name2 })
    if (res.code === 200) {
      setVisible2(false)
        setToastShow(true)
        setWishName({ name1: "已保存自", name2: wishName.name2 })
        getGoodsData()
        setTimeout(() => {
          setToastShow(false)
        }, 3000)
    }
  }

  const showHeart = () => {
    let res = goodsData.map((item: any) => {
      heartArr.map((itm: number) => {
        if (item.id === itm) {
          item.isHeart = true
        }
      })
      return item
    })
    setUserGoodsData(res)
  }

  useEffect(() => {
    getNavData()
    getGoodsData()
    getWishData()
  }, [])

  useEffect(() => showHeart(), [goodsData])
  return <div onWheel={(e) => {
    if (e.deltaY > 0) {
      setHeight(0)
    } else {
      setHeight(64)
    }
  }}>
    <div className={header}>
      <div className={search}>
        <div className={content}>
          <div style={{ flex: "1", display: "flex" }} onClick={()=> navigate("/search")}>
            <div className={btn}><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" role="presentation" focusable="false" style={{ display: "block", fill: "none", height: "16px", width: "16px", stroke: "currentcolor", strokeWidth: "4", overflow: "visible" }}><path fill="none" d="M13 24a11 11 0 1 0 0-22 11 11 0 0 0 0 22zm8-3 9 9"></path></svg></div>
            <div className={title}>
              <h3>任何地方</h3>
              <span>任意一周  ·  添加房客</span>
            </div>
          </div>
          <div className={btn}><div style={{ width: "37px", height: "37px", border: "1px solid #ddd", boxSizing: "border-box", display: "flex", alignItems: 'center', justifyContent: "center", borderRadius: "36px" }}><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" aria-hidden="true" role="presentation" focusable="false" style={{ display: "block", height: "16px", width: "16px" }}><path d="M5 8a3 3 0 0 1 2.83 2H14v2H7.83A3 3 0 1 1 5 8zm0 2a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm6-8a3 3 0 1 1-2.83 4H2V4h6.17A3 3 0 0 1 11 2zm0 2a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"></path></svg></div></div>
        </div>
      </div>
      <div className={navBox}>
        <ul className={nav}>
          {
            navData.map((item: any, i: number) => <li onClick={() => {
              setIndex(i)
              setCategoryId(item.id)
            }} className={index === i ? active : ''} key={item.id}>
              <img src={item.img} alt="" />
              <span>{item.title}</span>
            </li>)
          }

        </ul>
      </div>
    </div>
    <div className={main} >
      <div className={totalPrice}>
        <div>
          <h2>显示总价</h2>
          <span>税前价格，包含所有费用</span>
        </div>
        <Switch
          style={{ "--width": "46px", "--checked-color": "#222" }}
        />
      </div>
      {
        goodsData.filter((item: any) => item.categoryId === categoryId).map((item: any) => <div  key={item.id} className={goodsItem}>
          <div style={{ position: 'relative' }}>
            <Swiper>{item.banners.map((itm: any) => (
              <Swiper.Item key={itm}>
                <img onClick={()=> navigate("/details",{state:{proinformation:item,date:""}})} src={itm} alt="" />
              </Swiper.Item>
            ))}</Swiper>
            <div style={{ position: 'absolute', top: "15px", right: "15px" ,zIndex:'10'}} onClickCapture={() => addWish(item)}>
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" role="presentation" focusable="false" style={{ display: "block", fill: `${item.isHeart ? "#FF385C" : "rgba(0,0,0,0.5)"}`, height: "24px", width: "24px", stroke: "#fff", strokeWidth: 2, overflow: "visible" }}><path d="M16 28c7-4.73 14-10 14-17a6.98 6.98 0 0 0-7-7c-1.8 0-3.58.68-4.95 2.05L16 8.1l-2.05-2.05a6.98 6.98 0 0 0-9.9 0A6.98 6.98 0 0 0 2 11c0 7 7 12.27 14 17z"></path></svg>
            </div>
          </div>
          <div onClick={()=> navigate("/details",{state:{proinformation:item,date:""}})}>
          <div className={proInfo}><p>{item.proname}</p><span>★ {item.score}</span></div>
          <span>距离你 {item.distance} 公里</span>
          <div>{item.time}</div>
          <s>￥{formatNum(item.price)}</s> 晚
          </div>
        </div>)
      }
      {
        toastShow && <ToastBase img={img} name={wishName} ></ToastBase>
      }
    </div>
    <Bottom height={height} index={0} />

    <Popup
      showCloseButton
      visible={visible}
      onMaskClick={() => {
        setVisible(false)
      }}
      bodyStyle={{
        borderTopLeftRadius: '8px',
        borderTopRightRadius: '8px',
        minHeight: '40vh',
      }}
    >
      <div className={wishBox}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", borderBottom: "1px solid #ddd" }}>
          <h2>你的心愿单</h2>
        </div>
        <div style={{ overflowY: "auto", padding: '20px 16px' }}>
          <div className={wishItem} onClick={() => { setVisible(false); setVisible2(true) }}>
            <img src="https://a0.muscache.com/im/pictures/da1a2f06-efb0-4079-abce-0f6fc82089e0.jpg" alt="" />
            <span>创建新的心愿单</span>
          </div>
          {
            wishData.map((item: any) => <div onClick={() => addWishListChildren(item)} key={item.id} className={wishItem}>
              <img src={item.children[0]?.banners[0] || "https://a0.muscache.com/im/pictures/1366a633-171a-4592-9a51-cd4e6f46a897.jpg"} alt="" />
              <span>{item.title}</span>
            </div>)
          }
        </div>
      </div>
    </Popup>
    <Popup
      showCloseButton
      visible={visible2}
      onMaskClick={() => {
        setVisible(false)
      }}
      bodyStyle={{
        borderTopLeftRadius: '8px',
        borderTopRightRadius: '8px',
        minHeight: '40vh',
      }}
    >
      <div className={wishBox}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "center", borderBottom: "1px solid #ddd" }}>
          <h2>为此心愿单命名</h2>
        </div>
        <div style={{ padding: "32px 16px", borderBottom: "1px solid #ddd" }}>
          <input style={{ width: "99%", height: "52px", borderRadius: "10px", textIndent: "10px", border: "2px solid #B0B0B0" }} type="text" placeholder='名称' onChange={(e) => setWishName({ name1: "", name2: e.target.value })} />
          <span style={{ display: "block", marginTop: "10px", color: "#717171" }}>不能超过50个字符</span>
        </div>
        <Button style={{ margin: "14px 24px", width: "88%", height: "44px", background: "#222", color: "#fff", fontSize: "14px", fontWeight: "bold", borderRadius: "8px" }} disabled={wishName ? false : true} onClick={addWishList}>创建</Button>
      </div>
    </Popup>
  </div>
}
export default Explore